package com.weiyuwqj.admin.controller.admin.sys;

import com.weiyuwqj.api.service.SysRoleResourceService;
import com.weiyuwqj.api.service.SysRoleService;
import com.weiyuwqj.api.common.Paginator;
import com.weiyuwqj.api.constant.Message;
import com.weiyuwqj.api.model.SysRole;
import com.weiyuwqj.api.model.SysRoleResource;
import com.weiyuwqj.api.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhangyong on 2016/7/20.
 */
@Controller
@RequestMapping("/admin/role")
public class RoleController {

    @Autowired
    SysRoleService roleService;

    @Autowired
    SysRoleResourceService resourceService;

    @ResponseBody
    @RequestMapping("/list")
    public Object list(Paginator p,String roleName){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("roleName", roleName);
        return roleService.getList(p,map);
    }

    @ResponseBody
    @RequestMapping("/getOne")
    public Object getOne(Integer id){
        Map map=new HashMap();
        map.put("role",roleService.selectByKey(id));
        map.put("resource", resourceService.getOneByRoleId(id));
        return map;
    }

    @ResponseBody
    @RequestMapping("/modify")
    public Object modify(SysRole role,String sources){
        roleService.updateNotNull(role);
        SysRoleResource resource=new SysRoleResource();
        int roleId=role.getId();
        resource.setRoleId(roleId);
        resourceService.delByRoleId(roleId);
        if(!StringUtils.isNull(sources)){
            String[] s=sources.split(",");
            for(int i=0;i<s.length;i++){
                resource.setSourceId(Integer.parseInt(s[i]));
                resourceService.save(resource);
            }

        }
        return Message.OK;
    }

    @ResponseBody
    @RequestMapping("/add")
    public Object add(SysRole role,String sources){
        roleService.add(role,sources);
        return Message.OK;
    }

    //后台角色未分页列表
    @ResponseBody
    @RequestMapping("/listNoPage")
    public Object listNoPage(){
        Map map=new HashMap();
        return roleService.getList(map);
    }
}
